package cn.uce.common.aspect;

import cn.uce.common.annotation.TargetDataSource;
import cn.uce.common.dataSource.DataSourceInvoke;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.reflect.Method;

/**
 * sqlMap dao层切面
 * @author Sunny
 * @date 2018-9-22
 */
public class DataSourceAspect implements MethodBeforeAdvice, AfterReturningAdvice, Ordered {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public DataSourceAspect() {
        //do nothing
    }

    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        DataSourceInvoke.clearDataSource();
    }

    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        TargetDataSource dataSource = AnnotationUtils.findAnnotation(method,TargetDataSource.class);
        if(null == dataSource){
            //方法没找到，再找类
            dataSource = AnnotationUtils.findAnnotation(method.getDeclaringClass(),TargetDataSource.class);;
        }
        if(dataSource instanceof TargetDataSource){
            DataSourceInvoke.putDataSource(dataSource.value());
//            logger.info("===============切换数据源[{}]===============",dataSource.value());
        }
    }

    @Override
    public int getOrder() {
        return PriorityOrdered.HIGHEST_PRECEDENCE+1;
    }
}
